<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import { i18n } from 'boot/i18n'
import { date, Notify } from 'quasar'
import api from 'src/api'
import type { MeetingReservation, ListReservationsParams, ReservationStatus, RoomType } from 'src/api/service'

const tc = i18n.global.tc

// 会议筛选
const filterDate = ref({
  from: date.formatDate(date.subtractFromDate(new Date(), { days: 30 }), 'YYYY/MM/DD'),
  to: date.formatDate(new Date(), 'YYYY/MM/DD')
})
const filterStatus = ref<ReservationStatus | 'all'>('all')
const filterRoomType = ref<RoomType | 'all'>('all')
const filterQuery = ref('')

// 会议数据
const meetings = ref<MeetingReservation[]>([])
const loadingMeetings = ref(false)
const pagination = ref({
  page: 1,
  rowsPerPage: 10,
  rowsNumber: 0
})

// 搜索条件是否已修改
const filtersChanged = ref(false)

// 格式化日期函数 (接受时间戳 number 或 ISO 字符串)
const formatDate = (timestampOrString: number | string | undefined | null): string => {
  if (!timestampOrString) return ''
  let timestampMs: number
  if (typeof timestampOrString === 'number') {
    timestampMs = timestampOrString * 1000
  } else {
    try {
      timestampMs = new Date(timestampOrString).getTime()
    } catch (e) {
      return 'Invalid Date'
    }
  }
  if (isNaN(timestampMs)) return 'Invalid Date'
  return date.formatDate(timestampMs, 'YYYY-MM-DD HH:mm')
}

// 获取会议列表
const fetchMeetings = async (page = 1, rowsPerPage = pagination.value.rowsPerPage) => {
  loadingMeetings.value = true
  const params: ListReservationsParams = {
    page,
    page_size: rowsPerPage,
    start_time_start: filterDate.value?.from ? Math.floor(new Date(filterDate.value.from + ' 00:00:00').getTime() / 1000) : undefined,
    start_time_end: filterDate.value?.to ? Math.floor(new Date(filterDate.value.to + ' 23:59:59').getTime() / 1000) : undefined,
    status: filterStatus.value === 'all' ? undefined : filterStatus.value,
    room_type: filterRoomType.value === 'all' ? undefined : filterRoomType.value,
    meeting_code: filterQuery.value || undefined,
    'as-admin': true
  }

  // 移除 undefined 的参数
  Object.keys(params).forEach(keyStr => {
    const key = keyStr as keyof ListReservationsParams // 类型断言
    if (params[key] === undefined) {
      delete params[key]
    }
  })

  try {
    const response = await api.service.txMeeting.listReservations(params)
    meetings.value = response.data.results || []
    pagination.value.rowsNumber = response.data.count || 0
    pagination.value.page = page
    pagination.value.rowsPerPage = rowsPerPage
  } catch (error) {
    console.error('Error fetching admin meetings:', error)
    Notify.create({
      message: tc('获取会议列表失败'),
      type: 'negative',
      icon: 'error',
      position: 'top'
    })
    meetings.value = []
    pagination.value.rowsNumber = 0
  } finally {
    loadingMeetings.value = false
  }
}

// 监听筛选条件变化
watch([() => filterDate.value.from, () => filterDate.value.to, filterStatus, filterRoomType, filterQuery], () => {
  // 设置搜索条件已修改
  filtersChanged.value = true
  // 清空会议数据
  meetings.value = []
  pagination.value.rowsNumber = 0
})

// 搜索会议
const searchMeetings = () => {
  // 清除会议号中的空格和连字符
  if (filterQuery.value) {
    // 去除所有空格和连字符
    filterQuery.value = filterQuery.value.replace(/[\s-]/g, '')
  }

  filtersChanged.value = false
  fetchMeetings(1)
}

// 处理表格请求 (分页、排序等)
const handleTableRequest = (props: { pagination: { page: number, rowsPerPage: number } }) => {
  const {
    page,
    rowsPerPage
  } = props.pagination
  fetchMeetings(page, rowsPerPage)
}

// 当前选中的会议
const selectedMeeting = ref<MeetingReservation | null>(null)
const meetingDetailsOpen = ref(false)
const loadingMeetingDetails = ref(false)

// 关闭会议详情
const closeMeetingDetails = () => {
  meetingDetailsOpen.value = false
  selectedMeeting.value = null
}

// 显示会议详情 (调用 API 获取最新数据)
const showMeetingDetails = async (meetingId: string) => {
  loadingMeetingDetails.value = true
  meetingDetailsOpen.value = true
  selectedMeeting.value = null
  try {
    const response = await api.service.txMeeting.getReservationDetail(meetingId, true)
    selectedMeeting.value = response.data
  } catch (error) {
    console.error('Error fetching meeting details:', error)
    Notify.create({
      message: tc('获取会议详情失败'),
      type: 'negative',
      icon: 'error',
      position: 'top'
    })
    closeMeetingDetails()
  } finally {
    loadingMeetingDetails.value = false
  }
}

// 强制释放会议资源 (调用取消接口)
const cancellingMeeting = ref(false)
const forceReleaseMeeting = async () => {
  if (!selectedMeeting.value || cancellingMeeting.value) return

  const meetingId = selectedMeeting.value.id
  cancellingMeeting.value = true
  const dismiss = Notify.create({
    message: tc('正在取消/释放会议...'),
    type: 'ongoing',
    position: 'center',
    timeout: 0
  })

  try {
    await api.service.txMeeting.cancelReservation(meetingId)
    dismiss()
    Notify.create({
      message: tc('会议已取消/释放'),
      type: 'positive',
      icon: 'check',
      position: 'top'
    })
    closeMeetingDetails()
    fetchMeetings(pagination.value.page)
  } catch (error) {
    dismiss()
    console.error('Error cancelling meeting:', error)
    Notify.create({
      message: tc('取消/释放会议失败'),
      type: 'negative',
      icon: 'error',
      position: 'top'
    })
  } finally {
    cancellingMeeting.value = false
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchMeetings()
})
</script>

<template>
  <q-scroll-area style="height: calc(100vh - 50px)">
    <div class="q-pa-md">
      <h5 class="q-mt-none q-mb-md">{{ tc('预定管理') }}</h5>

      <!-- 会议筛选 -->
      <div class="q-mb-md q-pa-md border-container">
        <div class="row q-col-gutter-md items-center">
          <!-- 日期范围 -->
          <div class="col-12 col-md-4">
            <q-input filled v-model="filterDate.from" :label="tc('开始日期')" dense>
              <template v-slot:append>
                <q-icon name="event" class="cursor-pointer">
                  <q-popup-proxy cover transition-show="scale" transition-hide="scale">
                    <q-date v-model="filterDate.from" mask="YYYY/MM/DD">
                      <div class="row items-center justify-end">
                        <q-btn v-close-popup :label="tc('确定')" color="primary" flat/>
                      </div>
                    </q-date>
                  </q-popup-proxy>
                </q-icon>
              </template>
            </q-input>
          </div>

          <div class="col-12 col-md-4">
            <q-input filled v-model="filterDate.to" :label="tc('结束日期')" dense>
              <template v-slot:append>
                <q-icon name="event" class="cursor-pointer">
                  <q-popup-proxy cover transition-show="scale" transition-hide="scale">
                    <q-date v-model="filterDate.to" mask="YYYY/MM/DD">
                      <div class="row items-center justify-end">
                        <q-btn v-close-popup :label="tc('确定')" color="primary" flat/>
                      </div>
                    </q-date>
                  </q-popup-proxy>
                </q-icon>
              </template>
            </q-input>
          </div>

          <!-- 会议室类型 -->
          <div class="col-12 col-md-4">
            <q-select v-model="filterRoomType" :options="[
              { label: tc('全部类型'), value: 'all' },
              { label: tc('50方'), value: 50 },
              { label: tc('100方'), value: 100 },
              { label: tc('300方'), value: 300 },
              { label: tc('500方'), value: 500 },
              { label: tc('1000方'), value: 1000 }
            ]" emit-value map-options filled dense :label="tc('会议室类型')"/>
          </div>

          <!-- 会议状态 -->
          <div class="col-12 col-md-4">
            <q-select v-model="filterStatus" :options="[
              { label: tc('全部状态'), value: 'all' },
              { label: tc('已预定'), value: 'reserved' },
              { label: tc('已取消'), value: 'cancelled' }
            ]" emit-value map-options filled dense :label="tc('预定状态')"/>
          </div>

          <!-- 搜索框 -->
          <div class="col-12 col-md-4">
            <q-input v-model="filterQuery" filled dense :label="tc('搜索会议号')" clearable>
              <template v-slot:append>
                <q-icon name="search"/>
              </template>
            </q-input>
          </div>

          <!-- 搜索按钮 -->
          <div class="col-12 col-md-4">
            <q-btn color="primary" :label="tc('搜索')" icon="search" @click="searchMeetings"
                   :loading="loadingMeetings"/>
          </div>
        </div>
      </div>

      {{}}

      <!-- 搜索条件改变提示 -->
      <q-banner v-if="filtersChanged" class="bg-blue-1 text-blue-9 q-mb-md">
        <template v-slot:avatar>
          <q-icon name="info" color="info"/>
        </template>
        {{ tc('搜索条件已更新，请点击搜索按钮查询数据') }}
      </q-banner>

      <!-- 会议列表 -->
      <q-table flat bordered :rows="meetings" :columns="[
        { name: 'subject', label: tc('会议主题'), field: 'subject', align: 'left', sortable: true },
        { name: 'tx_meeting_code', label: tc('会议号'), field: 'tx_meeting_code', align: 'left' },
        {
          name: 'start_time',
          label: tc('开始时间'),
          field: 'start_time',
          format: val => formatDate(val),
          align: 'left',
          sortable: true
        },
        {
          name: 'end_time',
          label: tc('结束时间'),
          field: 'end_time',
          format: val => formatDate(val),
          align: 'left',
          sortable: true
        },
        { name: 'room_type', label: tc('会议室类型'), field: 'room_type', format: val => `${val}方`, align: 'left' },
        { name: 'user', label: tc('预定人'), field: row => `${row.user?.full_name || 'N/A'} (${row.user?.username || 'N/A'})`, align: 'left' },
        {
          name: 'status',
          label: tc('预定状态'),
          field: 'status',
          align: 'left'
        },
        {
          name: 'room_reserve_status',
          label: tc('会议室预留状态'),
          field: 'room_reserve_status',
          align: 'left'
        },
        {
          name: 'actions',
          label: tc('操作'),
          field: 'id',
          align: 'left'
        }
      ]" row-key="id" :pagination="pagination" :loading="loadingMeetings" @request="handleTableRequest"
               class="q-mb-md">
        <template v-slot:body-cell-status="props">
          <q-td :props="props">
            <q-chip :color="props.row.status === 'reserved' ? 'positive' : 'grey'" text-color="white" dense square>
              {{ props.row.status === 'reserved' ? tc('已预定') : tc('已取消') }}
            </q-chip>
          </q-td>
        </template>

        <template v-slot:body-cell-room_reserve_status="props">
          <q-td :props="props">
            <q-chip
              :color="props.row.room_reserve_status === 'reserved' ? 'positive' : props.row.room_reserve_status === 'wait' ? 'warning' : 'negative'"
              text-color="white" dense square>
              {{
                props.row.room_reserve_status === 'wait' ? tc('待预留') : props.row.room_reserve_status === 'unreserved' ?
                  tc('预留失败') : props.row.room_reserve_status === 'reserved' ? tc('已预留') : props.row.room_reserve_status ===
                  'unreleased' ? tc('释放失败') : props.row.room_reserve_status === 'released' ? tc('已释放') :
                    props.row.room_reserve_status
              }}
            </q-chip>
          </q-td>
        </template>

        <template v-slot:body-cell-actions="props">
          <q-td :props="props">

            <div class="row justify-start">
              <q-btn flat dense round color="primary" icon="info" @click="showMeetingDetails(props.row.id)">
                <q-tooltip>{{ tc('查看详情') }}</q-tooltip>
              </q-btn>
              <q-btn v-if="props.row.status === 'reserved'" flat dense round icon="cancel" color="negative"
                     @click="selectedMeeting = props.row; forceReleaseMeeting()">
                <q-tooltip>{{ tc('取消/释放会议') }}</q-tooltip>
              </q-btn>
            </div>

          </q-td>
        </template>
      </q-table>

      <!-- 会议详情 Dialog -->
      <q-dialog v-model="meetingDetailsOpen" persistent @hide="closeMeetingDetails">
        <q-card style="min-width: 450px">
          <q-card-section class="row items-center">
            <div class="text-h6">{{ tc('会议详情') }}</div>
            <q-space/>
            <q-btn icon="close" flat round dense v-close-popup/>
          </q-card-section>

          <q-separator/>

          <q-card-section v-if="loadingMeetingDetails">
            <q-inner-loading showing>
              <q-spinner-gears size="50px" color="primary"/>
            </q-inner-loading>
            <div style="height: 300px;"></div>
          </q-card-section>

          <q-card-section v-else-if="selectedMeeting">
            <div class="q-mb-sm"><span class="text-subtitle2">{{ tc('会议主题') }}:</span> {{ selectedMeeting.subject }}
            </div>
            <div class="q-mb-sm"><span class="text-subtitle2">{{ tc('会议号') }}:</span> {{
                selectedMeeting.tx_meeting_code
              }}
            </div>
            <div class="q-mb-sm"><span class="text-subtitle2">{{ tc('预定时间') }}:</span> {{
                formatDate(selectedMeeting.start_time)
              }} - {{ formatDate(selectedMeeting.end_time) }}
            </div>
            <div class="q-mb-sm"><span class="text-subtitle2">{{ tc('会议室预留时间') }}:</span> {{
                formatDate(selectedMeeting.room_reserve_start)
              }} - {{ formatDate(selectedMeeting.room_reserve_end) }}
            </div>
            <div class="q-mb-sm"><span class="text-subtitle2">{{ tc('会议室类型') }}:</span>
              {{ selectedMeeting.room_type }}方
            </div>
            <div class="q-mb-sm"><span class="text-subtitle2">{{ tc('预定人') }}:</span> {{
                selectedMeeting.user?.full_name
              }}
              ({{ selectedMeeting.user?.username }})
            </div>
            <div class="q-mb-sm">
              <span class="text-subtitle2">{{ tc('预定状态') }}:</span>
              <q-chip :color="selectedMeeting.status === 'reserved' ? 'positive' : 'grey'" text-color="white" dense
                      square>
                {{ selectedMeeting.status === 'reserved' ? tc('已预定') : tc('已取消') }}
              </q-chip>
            </div>
            <div class="q-mb-sm">
              <span class="text-subtitle2">{{ tc('会议室预留状态') }}:</span>
              <q-chip
                :color="selectedMeeting.room_reserve_status === 'reserved' ? 'positive' : selectedMeeting.room_reserve_status === 'wait' ? 'warning' : 'negative'"
                text-color="white" dense square>
                {{
                  selectedMeeting.room_reserve_status === 'wait' ? tc('待预留') : selectedMeeting.room_reserve_status ===
                  'unreserved' ? tc('预留失败') : selectedMeeting.room_reserve_status === 'reserved' ? tc('已预留') :
                    selectedMeeting.room_reserve_status === 'unreleased' ? tc('释放失败') : selectedMeeting.room_reserve_status
                    ===
                    'released' ? tc('已释放') : selectedMeeting.room_reserve_status
                }}
              </q-chip>

            </div>

            <div class="q-mb-sm">
              <span class="text-subtitle2">{{ tc('预留信息') }}:</span>
              <div v-if="selectedMeeting.room_reserve_desc" class="q-mt-xs">{{
                  selectedMeeting.room_reserve_desc
                }}
              </div>
            </div>

            <div class="q-mb-sm">
              <span class="text-subtitle2">{{ tc('腾讯会议加入链接') }}:</span>
              <a :href="selectedMeeting.tx_join_url" target="_blank" class="text-primary">{{
                  selectedMeeting.tx_join_url
                }}</a>
            </div>
            <div class="q-mb-sm">
              <span class="text-subtitle2">{{ tc('会前提醒') }}:</span> {{
                selectedMeeting.advance_notice_seconds / 60
              }} {{
                tc('分钟')
              }}
            </div>

            <div v-if="selectedMeeting.email_notice">
              <q-separator class="q-my-md"/>
              <div class="text-subtitle1">{{ tc('邮件通知详情') }}</div>
              <div class="q-mb-sm"><span class="text-subtitle2">{{ tc('状态') }}:</span> {{
                  selectedMeeting.email_notice.status
                }}
              </div>
              <div class="q-mb-sm"><span class="text-subtitle2">{{ tc('接收人') }}:</span> {{
                  selectedMeeting.email_notice.receiver
                }}
              </div>
              <div class="q-mb-sm"><span class="text-subtitle2">{{ tc('发送时间') }}:</span> {{
                  formatDate(selectedMeeting.email_notice.send_time)
                }}
              </div>
              <div v-if="selectedMeeting.email_notice.status_desc" class="text-caption text-negative">{{
                  selectedMeeting.email_notice.status_desc
                }}
              </div>
            </div>

          </q-card-section>

          <q-separator/>

          <q-card-actions align="right">
            <q-btn v-if="selectedMeeting?.status === 'reserved'" :label="tc('取消/释放会议')" color="negative"
                   @click="forceReleaseMeeting" :loading="cancellingMeeting" :disable="cancellingMeeting"></q-btn>
            <q-btn :label="tc('关闭')" color="grey" flat v-close-popup></q-btn>
          </q-card-actions>
        </q-card>
      </q-dialog>
    </div>
  </q-scroll-area>
</template>

<style scoped>
.border-container {
  border: 1px solid #d0d0d0;
  border-radius: 4px;
}
</style>
